package com.zhixing.pay.controller;

import com.zhixing.common.annotation.Driver;
import com.zhixing.common.annotation.Passenger;
import com.zhixing.common.exception.ZhixingException;
import com.zhixing.common.utils.Res;
import com.zhixing.common.utils.UserContext;
import com.zhixing.pay.domain.dto.TransactionDTO;
import com.zhixing.pay.domain.vo.WalletInfoVO;
import com.zhixing.pay.service.WalletService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;

import static com.zhixing.common.domain.enums.HttpStatus.PAYMENT_AMOUNT_ERROR;
import static com.zhixing.common.domain.enums.HttpStatus.REMIT_AMOUNT_ERROR;

/**
 * 钱包接口
 */
@Slf4j
@RestController
@RequestMapping("/wallet")
@RequiredArgsConstructor
public class WalletController {

    private final WalletService walletService;

    /**
     * 获取钱包信息
     * @return WalletInfoVO 钱包信息
     */
    @GetMapping("/walletInfo")
    public Res<WalletInfoVO> getWalletInfo() {
        Integer userId = UserContext.getUserInfo().getId();
        log.info("支付服务调用，获取钱包信息，用户id：{}", userId);
        return Res.ok(walletService.getWalletInfo(userId));
    }

    /**
     * 充值或提现
     * @param transactionDTO 充值或提现信息
     * @return 操作结果
     */
    @PutMapping("/rechargeOrWithdrawal")
    public Res<Void> rechargeOrWithdrawal(@Validated @RequestBody TransactionDTO transactionDTO) {
        Integer userId = UserContext.getUserInfo().getId();
        log.info("支付服务调用，充值或提现，用户id：{}", userId);
        walletService.rechargeOrWithdrawal(userId, transactionDTO);
        return Res.ok();
    }

    /**
     * 支付订单
     * @param realPayment 实际支付
     * @return 操作结果
     */
    @Passenger
    @PutMapping("/payOrder")
    public Res<Void> payOrder(@RequestParam BigDecimal realPayment) {
        if (realPayment.compareTo(new BigDecimal(0)) <= 0 ||
                realPayment.compareTo(new BigDecimal(100000)) >= 0 || realPayment.scale() > 2) {
            throw new ZhixingException(PAYMENT_AMOUNT_ERROR);
        }
        Integer userId = UserContext.getUserInfo().getId();
        log.info("支付服务调用，支付订单，用户id：{}", userId);
        walletService.payOrder(realPayment, userId);
        return Res.ok();
    }

    /**
     * 司机打款
     * @param realIncome 实际收入
     * @return 操作结果
     */
    @Driver
    @PutMapping("/driverRemit")
    public Res<Void> driverRemit(@RequestParam BigDecimal realIncome) {
        if (realIncome.compareTo(new BigDecimal(0)) <= 0 ||
                realIncome.compareTo(new BigDecimal(100000)) >= 0 || realIncome.scale() > 2) {
            throw new ZhixingException(REMIT_AMOUNT_ERROR);
        }
        Integer userId = UserContext.getUserInfo().getId();
        log.info("支付服务调用，司机打款，用户id：{}", userId);
        walletService.driverRemit(realIncome, userId);
        return Res.ok();
    }
}
